import { Injectable, OnModuleInit } from '@nestjs/common';
import { ToolUtil } from '@/utils/tool.util';
import { UserService } from '@/modules/user/user.service';
import { RoleService } from './modules/role/role.service';
import { PermissionService } from './modules/permission/permission.service';
import { PermissionTypeEnum } from './modules/permission/entities/permission.entity';
import { flatMenu } from './static/menu.js';

@Injectable()
export class AppService implements OnModuleInit {
  constructor(
    private readonly userService: UserService,
    private readonly roleService: RoleService,
    private readonly permissionService: PermissionService,
    private readonly toolUtil: ToolUtil,
  ) {}

  async onModuleInit() {
    let adminPermission = [];
    const { rows } = await this.permissionService.findAll();
    if (rows.length > 0) {
      adminPermission = rows;
      console.log('permission无需初始化');
    } else {
      for (let index = 0; index < flatMenu.length; index++) {
        const element = flatMenu[index];
        const item = await this.permissionService.create({
          id: element.id,
          parentId: element.parentId,
          title: element.meta.title,
          type: element.isLeaf
            ? PermissionTypeEnum.MENU
            : PermissionTypeEnum.DIRECTORY,
          name: element.name,
          component: element.component,
          path: element.path,
          icon: element.icon,
        });
        adminPermission.push(item);
      }
      console.log('permission初始化成功');
    }
    const adminRole = await this.roleService.findOne('10000');
    if (adminRole) {
      console.log('role无需初始化');
    } else {
      await this.roleService.create({
        id: '10000',
        roleName: '超级管理员',
        permissions: adminPermission,
      });
      console.log(`role初始化成功`);
    }

    const admin = await this.userService.findOne('10000');
    if (admin) {
      console.log('user无需初始化');
    } else {
      const id = '10000';
      const initPassword = '123456';
      const { text: postPassword } = this.toolUtil.addSalt(initPassword, '');
      const { salt, text: password } = this.toolUtil.addSalt(postPassword);
      const createUserDto = {
        id,
        username: 'admin',
        password,
        salt,
        role: '10000', // 增加超级管理员权限
      };
      await this.userService.create(createUserDto);
      console.log(`user初始化成功 id:${id} password:${initPassword} `);
    }
  }
}
